package com.lzx.adx.report.support.strategy.media;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@Component
@Slf4j
@MediaType(MediaChannelConstant.HONOR)
public class HonorCallBackStrategy extends AbstractCallback{
    @Override
    public ResponseEntity callback(ReportDTO reportDTO, AccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String eventType = jsonObject.getString(callType);

        JSONObject jsonObject1 = JSONObject.parseObject(reportDTO.getExtend());

        String sspApiUrl = accountDTO.getSspApiUrl();
        Map<String, Object> paramsReq = new HashMap<>();
        paramsReq.put("trackId", reportDTO.getRequestId());
        paramsReq.put("conversionId", eventType);
        paramsReq.put("conversionTime", ts);
        paramsReq.put("advertiserId", jsonObject1.getString("aid"));
        String finalUrl = sspApiUrl + "?" + URLUtil.buildQuery(paramsReq, StandardCharsets.UTF_8);

        log.info("账号为{} 请求流水号{} 荣耀回调的请求的参数为{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), finalUrl);
        String result = HttpUtil.get(finalUrl);
        log.info("账号为{} 请求流水号{} 上报给荣耀转换响应的结果为{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), result);
        return ResponseEntity.ok(new Result());
    }
}
